package com.hp.bon.sgw.ctrl;

import org.jboss.resteasy.plugins.server.tjws.TJWSEmbeddedJaxrsServer;
import org.jboss.resteasy.plugins.spring.SpringBeanProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.hp.bon.sgw.util.LogTool;
import com.hp.bon.sgw.util.TJWSHelper;

public abstract class SpringProgramerStarter {
	private String startPropertyFile;
	private String[] springFiles;
	private String homeDirVar;
	public ClassPathXmlApplicationContext ctx = null;

	public abstract void runPeriodJob();

	public abstract boolean needStop();

	public String getStartPropertyFile() {
		return startPropertyFile;
	}

	public void setStartPropertyFile(String startPropertyFile) {
		this.startPropertyFile = startPropertyFile;
	}

	public String[] getSpringFiles() {
		return springFiles;
	}

	public void setSpringFiles(String[] springFiles) {
		this.springFiles = springFiles;
	}

	public String getHomeDirVar() {
		return homeDirVar;
	}

	public void setHomeDirVar(String homeDirVar) {
		this.homeDirVar = homeDirVar;
	}

	protected void loadStartParams() {
		LogTool.loadProperty(startPropertyFile);
		String homeDir = System.getProperty(homeDirVar);
		if (homeDir == null) {
			homeDir = System.getenv(homeDirVar);
		}
		if (homeDir == null) {
			System.out.println("warn no " + homeDirVar + " defined ,use current dir ");
			homeDir = ".";
		}
		System.setProperty(homeDirVar, homeDir);
	}

	public void start() {
		loadStartParams();
		ctx = new ClassPathXmlApplicationContext(springFiles);
		ctx.start();
		try {
			TJWSHelper tjwsHlp = ctx.getBean(TJWSHelper.class);
			if (tjwsHlp != null) {
				TJWSEmbeddedJaxrsServer server = tjwsHlp.getTjws();
				SpringBeanProcessor processor = new SpringBeanProcessor(tjwsHlp.getTjws().getDeployment().getDispatcher(), server.getDeployment().getRegistry(), server.getDeployment().getProviderFactory());
				processor.postProcessBeanFactory((ConfigurableListableBeanFactory) ctx.getBeanFactory());
			}
		} catch (Exception e) {

		}

		Thread shutdownHook = new Thread() {
			public void run() {
				System.out.println("MyShutDown thread started");
				SpringProgramerStarter.this.stop();
				System.out.println("MyShutDown thread finsihed");
			}
		};
		Runtime.getRuntime().addShutdownHook(shutdownHook);
	}

	public void stop() {
		try {
			ctx.stop();
		} finally {
			ctx.close();
			ctx = null;
		}

	}
}
